package com.yanq.liancar.activity;
/*
 *  @创建者     liyan
 *  @创建时间   2018/11/2  15:28
 *  @描述       ${救援图片上传}
 */


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxPhotoTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogChooseImage;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.SelectPhotosBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.Utils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UploadRescuePictureActivity extends BaseToolbarActivity {
    @BindView(R.id.image1)
    ImageView image1;
    @BindView(R.id.tv_upload1)
    TextView tvUpload1;
    @BindView(R.id.image2)
    ImageView image2;
    @BindView(R.id.tv_upload2)
    TextView tvUpload2;
    @BindView(R.id.image3)
    ImageView image3;
    @BindView(R.id.tv_upload3)
    TextView tvUpload3;
    @BindView(R.id.tv_pic4)
    TextView tvPic4;
    @BindView(R.id.image4)
    ImageView image4;
    @BindView(R.id.tv_upload4)
    TextView tvUpload4;
    @BindView(R.id.tv_kefu)
    TextView tvKefu;
    @BindView(R.id.tv_Nextstep)
    TextView tvNextstep;

    private Uri resultUri;
    private int succ,shopID;
    private File file1, file2,file3,file4;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.setStatusBar(this, true, false);
        setContentView(R.layout.activity_uploadrescuepicture);
        ButterKnife.bind(this);
        mTvTitle.setText("救援图片");

        shopID=getIntent().getIntExtra("shopID",0);
        getinitOkGo();
        SpannableString spannableString = new SpannableString("图四：救援完成后的拍照（搭电：照片需看清启动后仪表；换胎：照片需看清更换成功备胎和车牌）");
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red));
        spannableString.setSpan(colorSpan, 11, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan colorSpan3 = new ForegroundColorSpan(getResources().getColor(R.color.background_content));
        spannableString.setSpan(colorSpan3, 0, 11, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tvPic4.setText(spannableString);

        SpannableString spannableString1 = new SpannableString("无法拍照，请联系客服");
        ForegroundColorSpan colorSpan1 = new ForegroundColorSpan(getResources().getColor(R.color.main_color));
        spannableString1.setSpan(colorSpan1, 6, spannableString1.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan colorSpan4 = new ForegroundColorSpan(getResources().getColor(R.color.background_content));
        spannableString1.setSpan(colorSpan4, 0, 6, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tvKefu.setText(spannableString1);
    }

    @OnClick({R.id.tv_upload1, R.id.tv_upload2, R.id.tv_upload3, R.id.tv_upload4, R.id.tv_kefu,R.id.tv_Nextstep,R.id.image1,R.id.image2,R.id.image3,R.id.image4})
    public void onViewClicked(View view) {
        RxDialogChooseImage dialogChooseImage = new RxDialogChooseImage(this);
        switch (view.getId()) {
            case R.id.image1:
            case R.id.tv_upload1:
                succ=1;
                dialogChooseImage.show();
                break;
            case R.id.image2:
            case R.id.tv_upload2:
                succ=2;
                dialogChooseImage.show();
                break;
            case R.id.image3:
            case R.id.tv_upload3:
                succ=3;
                dialogChooseImage.show();
                break;
            case R.id.image4:
            case R.id.tv_upload4:
                succ=4;
                dialogChooseImage.show();
                break;
            case R.id.tv_kefu:
                break;
            case R.id.tv_Nextstep:
                Bundle bundle=new Bundle();
                bundle.putInt("shopID",shopID);
                RxActivityTool.skipActivity(this, CustomerSignatureActivity.class,bundle);
                break;
        }
    }

    private void initUCrop(Uri uri) {
        //Uri destinationUri = RxPhotoTool.createImagePathUri(this);

        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));

        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageName + ".jpeg"));

        Log.e("initUCrop: ", destinationUri + "");

        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.main_color));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.main_color));

        //开始设置
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);
        //设置图片在切换比例时的动画
        options.setImageToCropBoundsAnimDuration(666);
        //设置裁剪窗口是否为椭圆
        //        options.setOvalDimmedLayer(true);
        //设置是否展示矩形裁剪框
        // options.setShowCropFrame(false);
        //设置裁剪框横竖线的宽度
        //options.setCropGridStrokeWidth(20);
        //设置裁剪框横竖线的颜色
        //options.setCropGridColor(Color.GREEN);
        //设置竖线的数量
        //options.setCropGridColumnCount(2);
        //设置横线的数量
        //options.setCropGridRowCount(1);

        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(1000, 1000)
                .withOptions(options)
                .start(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        initMySelfImg(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initMySelfImg(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(data.getData());
                }

                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(RxPhotoTool.imageUriFromCamera);

                }

                break;
            case RxPhotoTool.CROP_IMAGE://普通裁剪后的处理
                resultUri = RxPhotoTool.cropImageUri;
                if (succ == 1) {
                    file1 = roadImageView(resultUri, image1);
                    initOkGo("drivingLicense",file1,"llc/api/RoadRescueController/insertRescueDrivingLicense");
                } else if (succ == 2){
                    file2 = roadImageView(resultUri, image2);
                    initOkGo("scenePhoto",file2,"llc/api/RoadRescueController/insertRescueScenePhoto");
                } else if (succ == 3) {
                    file3 = roadImageView(resultUri, image3);
                    initOkGo("processPhoto",file3,"llc/api/RoadRescueController/insertRescueProcessPhoto");
                }else if (succ == 4){
                    file4 = roadImageView(resultUri, image4);
                    initOkGo("finishPhoto",file4,"llc/api/RoadRescueController/insertRescueFinishPhoto");
                }
                break;

            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                if (resultCode == RESULT_OK) {
                    resultUri = UCrop.getOutput(data);
                    if (succ == 1) {
                        file1 = roadImageView(resultUri, image1);
                        initOkGo("drivingLicense",file1,"llc/api/RoadRescueController/insertRescueDrivingLicense");
                    } else if (succ == 2){
                        file2 = roadImageView(resultUri, image2);
                        initOkGo("scenePhoto",file2,"llc/api/RoadRescueController/insertRescueScenePhoto");
                    } else if (succ == 3) {
                        file3 = roadImageView(resultUri, image3);
                        initOkGo("processPhoto",file3,"llc/api/RoadRescueController/insertRescueProcessPhoto");
                    }else if (succ == 4){
                        file4 = roadImageView(resultUri, image4);
                        initOkGo("finishPhoto",file4,"llc/api/RoadRescueController/insertRescueFinishPhoto");
                    }
                } else if (resultCode == UCrop.RESULT_ERROR) {
                    final Throwable cropError = UCrop.getError(data);
                }
                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                RxToast.error(cropError.getMessage());
                Log.e("asd", "initMySelfImg: " + cropError.getMessage());
                break;
            default:
                break;
        }
    }

    //从Uri中加载图片 并将其转化成File文件返回
    private File roadImageView(Uri uri, ImageView imageView) {

        Glide.with(this).
                load(uri).
                thumbnail(0.5f).
                into(imageView);

        return (new File(RxPhotoTool.getImageAbsolutePath(this, uri)));
    }


    //图片上传
    private void initOkGo(String paramsName,File file,String url) {
        OkGo.<String>post(Config.s + url)
                .tag(this)
                .params(paramsName,file)
                .params("id", shopID)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean bean = gson.fromJson(response.body(), BaseBean.class);
                        if (bean.isIsSuccess()){
                            RxToast.success(bean.getOutputMessage());
                        }else {
                            RxToast.error(bean.getOutputMessage());
                        }
                    }
                });
    }

    //获取已经上传成功的图片
    private void getinitOkGo() {
        OkGo.<String>post(Config.s + "llc/api/RoadRescueController/selectPhotos")
                .tag(this)
                .params("shopid",shopID)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        SelectPhotosBean bean = gson.fromJson(response.body(), SelectPhotosBean.class);
                        if (bean.isIsSuccess()){
                          Glide.with(mContext).load(bean.getData().getRescueDrivingLicense()).into(image1);
                          Glide.with(mContext).load(bean.getData().getRescueProcessPhoto()).into(image3);
                          Glide.with(mContext).load(bean.getData().getRescueScenePhoto()).into(image2);
                          Glide.with(mContext).load(bean.getData().getFinishPhoto()).into(image4);
                        }else {
                            RxToast.error(bean.getOutputMessage());
                        }
                    }
                });
    }

}
